package com.mokairui.performance;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * @Description 计算多个文件中 每个字母出现的次数
 * @Author Mokairui
 * @Since 2021/12/26
 */
public class TestWordCount {

    public static void main(String[] args) {
        demo(
                () -> new ConcurrentHashMap<String, LongAdder>(),

                (map, words) -> {
                    for (String word : words) {

                        // 如果缺少此 key, 则计算生成一个 value, 然后将 key value 放入 map
                        LongAdder value = map.computeIfAbsent(word, key -> new LongAdder());
                        // 执行累加
                        value.increment();
                    }
                }
        );
    }

    private static <V> void demo(Supplier<Map<String, V>> supplier, BiConsumer<Map<String, V>, List<String>> consumer) {
        Map<String, V> counterMap = supplier.get();

        List<Thread> ts = new ArrayList<>();
        for (int i = 1; i <= 26; i++) {
            int idx = i;
            Thread thread = new Thread(() -> {
                List<String> words = readFromFile(idx);
                consumer.accept(counterMap, words);
            });
            ts.add(thread);
        }

        ts.forEach(Thread::start);
        ts.forEach(it -> {
            try {
                it.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println(counterMap);
    }

    // 读取本地的文件
    private static List<String> readFromFile(int idx) {
        return null;
    }

}
